package com.example.jnnews;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AddArticleActivity extends AppCompatActivity {

    private EditText etTitle, etContent;
    private Button btnSubmit;
    private SharedPreferences prefs;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_article);

        prefs = getSharedPreferences("jnnews_prefs", MODE_PRIVATE);
        etTitle = findViewById(R.id.et_title);
        etContent = findViewById(R.id.et_content);
        btnSubmit = findViewById(R.id.btn_submit);

        btnSubmit.setOnClickListener(v -> submitArticle());
    }

    private void submitArticle() {
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();

        if (title.isEmpty() || content.isEmpty()) {
            Toast.makeText(this, "标题和内容不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取当前用户作为作者
        String author = prefs.getString("currentUser", "管理员");

        // 创建新文章
        Article newArticle = new Article(title, content, author);

        // 获取现有文章列表
        List<Article> articles = getArticles();
        articles.add(0, newArticle); // 添加到列表开头

        // 保存更新后的列表
        saveArticles(articles);

        Toast.makeText(this, "文章发布成功", Toast.LENGTH_SHORT).show();
        finish(); // 关闭当前界面
    }

    private List<Article> getArticles() {
        String json = prefs.getString("articles", "");
        if (json.isEmpty()) return new ArrayList<>();
        Type type = new TypeToken<ArrayList<Article>>(){}.getType();
        return gson.fromJson(json, type);
    }

    private void saveArticles(List<Article> articles) {
        String json = gson.toJson(articles);
        prefs.edit().putString("articles", json).apply();
    }
}